package com.kindergarten.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kindergarten.annotaion.KinderGartenLogger;
import com.kindergarten.pojo.Systemlog;
import com.kindergarten.pojo.User;
import com.kindergarten.service.ISystemlogService;
import com.kindergarten.utils.DateUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;

/**
 * 增强类 日志切面类
 */
@Aspect
@Component
public class KinderGartenLoggerAdvice {

    @Autowired
    ISystemlogService iSystemlogService;

    @Autowired
    HttpSession session;

    /**
     * 环绕增强
     * 只有目标方法上有@kinderGartenLogger注解修饰的方法，才会有日志环绕
     *
     * @param joinPoint
     */
    @Around("@annotation(kinderGartenLogger)")
    public Object aroundMethod(ProceedingJoinPoint joinPoint, KinderGartenLogger kinderGartenLogger) {
        User user = (User) session.getAttribute("user");
        //新增用户行为日志
        Systemlog systemlog = new Systemlog();
        systemlog.setLogtype(0);//0  普通日志
        systemlog.setNowuser(user.getUserName());//当前用户
        systemlog.setCreatetime(DateUtils.now()); // 日志时间
        String methodName = joinPoint.getSignature().getName();
        systemlog.setMethodName(methodName); //日志的方法
        systemlog.setLogDescription(kinderGartenLogger.logDescription()); // 日志描述信息

        Object[] parames = joinPoint.getArgs();
        systemlog.setMethodParms(this.parseParames(parames)); // 方法参数信息
        systemlog.setMethodType(kinderGartenLogger.methodType());//方法返回值类型

        Object result = null;
        try {

            System.out.println("目标方法" + methodName + "调用啦!");
            //调用目标方法
            result = joinPoint.proceed();
            //方法返回值信息
            systemlog.setMethodReturn(new ObjectMapper().writeValueAsString(result));
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            systemlog.setLogtype(0);//1 异常日志
            //异常信息
            systemlog.setExMessage(throwable.getMessage());
        }
        iSystemlogService.save(systemlog);
        return result;
    }

    private String parseParames(Object[] parames) {
        if (null == parames || parames.length <= 0) {
            return "";
        }
        StringBuffer param = new StringBuffer("传入参数 # 个:[ ");
        int i = 0;
        for (Object obj : parames) {
            i++;
            if (i == 1) {
                param.append(obj.toString());
                continue;
            }
            param.append(" ,").append(obj.toString());
        }
        return param.append(" ]").toString().replace("#", String.valueOf(i));
    }
}
